<template>
  <div class="expression-editor-demo">
    <el-container>
      <el-header class="demo-header">
        <h1>表达式编辑器示例</h1>
        <p>这是一个独立的表达式编辑器组件，支持智能提示、语法验证和动态示例生成</p>
      </el-header>

      <el-main class="demo-main">
        <el-row :gutter="24">
          <!-- 左侧：编辑器演示 -->
          <el-col :span="16">
            <el-card class="demo-card">
              <template #header>
                <div class="card-header">
                  <span>表达式编辑器</span>
                  <el-button-group size="small">
                    <el-button @click="loadPreset('basic')">基础示例</el-button>
                    <el-button @click="loadPreset('complex')">复杂示例</el-button>
                    <el-button @click="loadPreset('validation')">验证示例</el-button>
                    <el-button @click="loadPreset('date')">日期函数</el-button>
                    <el-button @click="loadPreset('number')">数学函数</el-button>
                    <el-button @click="loadPreset('dateNumber')">综合示例</el-button>
                  </el-button-group>
                </div>
              </template>

              <ExpressionEditor v-model="expression" :system-variables="systemVariables" :form-variables="formVariables"
                :show-variable-help="showVariableHelp" :show-example="showExample"
                placeholder="请输入表达式，支持 Ctrl+Space 触发智能提示" @validate="handleValidate" />

              <!-- 配置选项 -->
              <div class="demo-options">
                <el-divider content-position="left">配置选项</el-divider>
                <el-row :gutter="16">
                  <el-col :span="12">
                    <el-checkbox v-model="showVariableHelp">显示变量提示</el-checkbox>
                  </el-col>
                  <el-col :span="12">
                    <el-checkbox v-model="showExample">显示示例</el-checkbox>
                  </el-col>
                </el-row>
              </div>
            </el-card>

            <!-- 验证结果 -->
            <el-card class="demo-card" style="margin-top: 16px;">
              <template #header>
                <span>验证结果</span>
              </template>

              <div v-if="validationResult" class="validation-result">
                <el-descriptions :column="2" border>
                  <el-descriptions-item label="验证状态">
                    <el-tag :type="validationResult.isValid ? 'success' : 'danger'">
                      {{ validationResult.isValid ? '通过' : '失败' }}
                    </el-tag>
                  </el-descriptions-item>
                  <el-descriptions-item label="错误数量">
                    <el-tag type="danger">{{ validationResult.errors.length }}</el-tag>
                  </el-descriptions-item>
                  <el-descriptions-item label="警告数量">
                    <el-tag type="warning">{{ validationResult.warnings.length }}</el-tag>
                  </el-descriptions-item>
                  <el-descriptions-item label="表达式长度">
                    <el-tag type="info">{{ expression.length }} 字符</el-tag>
                  </el-descriptions-item>
                </el-descriptions>

                <!-- 详细错误信息 -->
                <div v-if="validationResult.errors.length > 0" class="error-details">
                  <h4>错误详情：</h4>
                  <ul>
                    <li v-for="(error, index) in validationResult.errors" :key="index">
                      <strong>{{ error.type }}:</strong> {{ error.message }}
                      <span v-if="error.position !== undefined"> (位置: {{ error.position }})</span>
                    </li>
                  </ul>
                </div>

                <!-- 警告信息 -->
                <div v-if="validationResult.warnings.length > 0" class="warning-details">
                  <h4>警告信息：</h4>
                  <ul>
                    <li v-for="(warning, index) in validationResult.warnings" :key="index">
                      <strong>{{ warning.type }}:</strong> {{ warning.message }}
                    </li>
                  </ul>
                </div>
              </div>
            </el-card>
          </el-col>

          <!-- 右侧：变量管理和文档 -->
          <el-col :span="8">
            <!-- 变量管理 -->
            <el-card class="demo-card">
              <template #header>
                <div class="card-header">
                  <span>变量管理</span>
                  <el-button size="small" @click="showVariableDialog = true">
                    <el-icon>
                      <Plus />
                    </el-icon>
                    添加变量
                  </el-button>
                </div>
              </template>

              <el-tabs v-model="activeVariableTab">
                <el-tab-pane label="系统变量" name="system">
                  <div class="variable-list">
                    <div v-for="(variable, index) in systemVariables" :key="index" class="variable-item">
                      <div class="variable-info">
                        <strong>{{ variable.name }}</strong>
                        <span class="variable-type">{{ variable.type }}</span>
                      </div>
                      <div class="variable-label">{{ variable.label }}</div>
                      <el-button size="small" type="danger" text @click="removeVariable('system', index)">
                        删除
                      </el-button>
                    </div>
                  </div>
                </el-tab-pane>

                <el-tab-pane label="表单变量" name="form">
                  <div class="variable-list">
                    <div v-for="(variable, index) in formVariables" :key="index" class="variable-item">
                      <div class="variable-info">
                        <strong>{{ variable.name }}</strong>
                        <span class="variable-type">{{ variable.type }}</span>
                      </div>
                      <div class="variable-label">{{ variable.label }}</div>
                      <el-button size="small" type="danger" text @click="removeVariable('form', index)">
                        删除
                      </el-button>
                    </div>
                  </div>
                </el-tab-pane>
              </el-tabs>
            </el-card>

            <!-- 语法文档 -->
            <el-card class="demo-card" style="margin-top: 16px;">
              <template #header>
                <span>语法文档</span>
              </template>

              <el-collapse v-model="activeDocSection">
                <el-collapse-item title="基本操作符" name="operators">
                  <div class="doc-content">
                    <ul>
                      <li><code>==</code> 等于</li>
                      <li><code>!=</code> 不等于</li>
                      <li><code>&gt;</code> 大于</li>
                      <li><code>&lt;</code> 小于</li>
                      <li><code>&gt;=</code> 大于等于</li>
                      <li><code>&lt;=</code> 小于等于</li>
                      <li><code>&amp;&amp;</code> 逻辑与</li>
                      <li><code>||</code> 逻辑或</li>
                      <li><code>!</code> 逻辑非</li>
                    </ul>
                  </div>
                </el-collapse-item>

                <el-collapse-item title="字符串函数" name="string-functions">
                  <div class="doc-content">
                    <ul>
                      <li><code>len(str)</code> 获取字符串长度</li>
                      <li><code>contains(str, substr)</code> 检查包含</li>
                      <li><code>startsWith(str, prefix)</code> 检查前缀</li>
                      <li><code>endsWith(str, suffix)</code> 检查后缀</li>
                      <li><code>matches(str, pattern)</code> 正则匹配</li>
                      <li><code>upper(str)</code> 转大写</li>
                      <li><code>lower(str)</code> 转小写</li>
                      <li><code>trim(str)</code> 去除空格</li>
                    </ul>
                  </div>
                </el-collapse-item>

                <el-collapse-item title="日期函数" name="date-functions">
                  <div class="doc-content">
                    <ul>
                      <li><code>now()</code> 获取当前时间</li>
                      <li><code>date(str[, format[, timezone]])</code> 解析日期字符串</li>
                      <li><code>duration(str)</code> 创建时间间隔</li>
                      <li><code>now().Year()</code> 获取年份</li>
                      <li><code>now().Month()</code> 获取月份</li>
                      <li><code>now().Day()</code> 获取日期</li>
                      <li><code>now().Hour()</code> 获取小时</li>
                      <li><code>now().Minute()</code> 获取分钟</li>
                      <li><code>now().Second()</code> 获取秒数</li>
                      <li><code>now().Format("2006-01-02")</code> 格式化日期</li>
                      <li><code>now().Add(duration("1h"))</code> 添加时间间隔</li>
                      <li><code>now().Before(date("2024-01-01"))</code> 时间比较</li>
                    </ul>
                  </div>
                </el-collapse-item>

                <el-collapse-item title="数学函数" name="number-functions">
                  <div class="doc-content">
                    <ul>
                      <li><code>abs(x)</code> 绝对值</li>
                      <li><code>ceil(x)</code> 向上取整</li>
                      <li><code>floor(x)</code> 向下取整</li>
                      <li><code>round(x)</code> 四舍五入</li>
                      <li><code>max(x, y, ...)</code> 最大值</li>
                      <li><code>min(x, y, ...)</code> 最小值</li>
                      <li><code>pow(x, y)</code> 幂运算</li>
                      <li><code>sqrt(x)</code> 平方根</li>
                      <li><code>log(x)</code> 自然对数</li>
                      <li><code>sin(x)</code> 正弦值</li>
                      <li><code>cos(x)</code> 余弦值</li>
                      <li><code>tan(x)</code> 正切值</li>
                    </ul>
                  </div>
                </el-collapse-item>

                <el-collapse-item title="示例表达式" name="examples">
                  <div class="doc-content">
                    <h5>基础示例</h5>
                    <ul>
                      <li><code>user.age &gt;= 18</code> 年龄检查</li>
                      <li><code>len(user.name) &gt; 0</code> 名称非空</li>
                      <li><code>contains(user.email, "@")</code> 邮箱格式</li>
                      <li><code>user.role == "admin"</code> 角色检查</li>
                    </ul>

                    <h5>日期函数示例</h5>
                    <ul>
                      <li><code>now().Year() &gt; 2023</code> 年份检查</li>
                      <li><code>now().Month() &gt;= 6</code> 月份检查</li>
                      <li><code>now().After(date("2023-01-01"))</code> 日期比较</li>
                      <li><code>date("2023-12-31").Before(now())</code> 过期检查</li>
                    </ul>

                    <h5>数学函数示例</h5>
                    <ul>
                      <li><code>abs(form.salary - 5000) &lt; 1000</code> 薪资范围</li>
                      <li><code>max(form.score1, form.score2) &gt;= 80</code> 最高分检查</li>
                      <li><code>round(form.amount / 100) * 100 == form.amount</code> 整百检查</li>
                      <li><code>sqrt(pow(x, 2) + pow(y, 2)) &lt; 10</code> 距离计算</li>
                    </ul>

                    <h5>复合表达式</h5>
                    <ul>
                      <li><code>form.score &gt;= 60 &amp;&amp; form.status == "active"</code> 复合条件</li>
                      <li><code>now().Year() &gt; 2023 &amp;&amp; abs(form.salary - 5000) &lt; 1000</code> 日期+数学</li>
                    </ul>
                  </div>
                </el-collapse-item>
              </el-collapse>
            </el-card>
          </el-col>
        </el-row>
      </el-main>
    </el-container>

    <!-- 添加变量对话框 -->
    <el-dialog v-model="showVariableDialog" title="添加变量" width="400px">
      <el-form :model="newVariable" label-width="80px">
        <el-form-item label="变量名">
          <el-input v-model="newVariable.name" placeholder="例如: user.name" />
        </el-form-item>
        <el-form-item label="显示名">
          <el-input v-model="newVariable.label" placeholder="例如: 用户姓名" />
        </el-form-item>
        <el-form-item label="类型">
          <el-select v-model="newVariable.type" placeholder="选择类型">
            <el-option label="字符串" value="string" />
            <el-option label="数字" value="number" />
            <el-option label="布尔值" value="boolean" />
            <el-option label="数组" value="array" />
            <el-option label="对象" value="object" />
          </el-select>
        </el-form-item>
        <el-form-item label="分类">
          <el-radio-group v-model="newVariable.category">
            <el-radio value="system">系统变量</el-radio>
            <el-radio value="form">表单变量</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="showVariableDialog = false">取消</el-button>
        <el-button type="primary" @click="addVariable">添加</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { Plus } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import ExpressionEditor from './ExpressionEditor.vue'
import type { Variable, ValidationResult } from './types'

// 响应式数据
const expression = ref('')
const validationResult = ref<ValidationResult | null>(null)
const showVariableHelp = ref(true)
const showExample = ref(true)
const activeVariableTab = ref('system')
const activeDocSection = ref(['operators'])
const showVariableDialog = ref(false)

// 系统变量
const systemVariables = ref<Variable[]>([
  { name: 'creator', label: '发起人', type: 'string' },
  { name: 'creatorId', label: '发起人id', type: 'number' },
  { name: 'baseNum', label: '基础个数', type: 'number' },
])

// 表单变量
const formVariables = ref<Variable[]>([
  { name: 'department', label: '部门', type: 'string' },
  { name: 'salary', label: '薪资', type: 'number' },
  { name: 'experience', label: '工作经验', type: 'number' },
  { name: 'skills', label: '技能列表', type: 'array' },
  { name: 'approved', label: '是否批准', type: 'boolean' },
  { name: 'comments', label: '备注', type: 'string' }
])

// 新变量表单
const newVariable = reactive({
  name: '',
  label: '',
  type: 'string',
  category: 'system'
})

// 预设表达式
const presets = {
  basic: 'user.age >= 18',
  complex: 'user.age >= 18 && form.department == "IT" && form.salary > 5000',
  validation: 'len(user.name) > 0 && contains(user.email, "@") && form.approved == true',
  date: 'now().Year() > 2023 && now().Month() >= 6',
  number: 'abs(form.salary - 5000) < 1000 && max(form.score1, form.score2) >= 80',
  dateNumber: 'now().After(date("2023-01-01")) && round(form.salary / 1000) * 1000 == form.salary'
}

// 方法
const handleValidate = (result: ValidationResult) => {
  validationResult.value = result
}

const loadPreset = (type: keyof typeof presets) => {
  expression.value = presets[type]
}

const addVariable = () => {
  if (!newVariable.name || !newVariable.label) {
    ElMessage.warning('请填写完整的变量信息')
    return
  }

  const variable: Variable = {
    name: newVariable.name,
    label: newVariable.label,
    type: newVariable.type
  }

  if (newVariable.category === 'system') {
    systemVariables.value.push(variable)
  } else {
    formVariables.value.push(variable)
  }

  // 重置表单
  Object.assign(newVariable, {
    name: '',
    label: '',
    type: 'string',
    category: 'system'
  })

  showVariableDialog.value = false
  ElMessage.success('变量添加成功')
}

const removeVariable = (category: 'system' | 'form', index: number) => {
  if (category === 'system') {
    systemVariables.value.splice(index, 1)
  } else {
    formVariables.value.splice(index, 1)
  }
  ElMessage.success('变量删除成功')
}
</script>

<style scoped>
.expression-editor-demo {
  min-height: 100vh;
  background-color: #f5f7fa;
}

.demo-header {
  background: white;
  border-bottom: 1px solid #e4e7ed;
  text-align: center;
  padding: 24px;
}

.demo-header h1 {
  margin: 0 0 8px 0;
  color: #303133;
}

.demo-header p {
  margin: 0;
  color: #606266;
  font-size: 14px;
}

.demo-main {
  padding: 24px;
}

.demo-card {
  margin-bottom: 16px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.demo-options {
  margin-top: 16px;
  padding-top: 16px;
}

.validation-result {
  margin-top: 16px;
}

.error-details,
.warning-details {
  margin-top: 16px;
}

.error-details h4,
.warning-details h4 {
  margin: 0 0 8px 0;
  color: #303133;
}

.error-details ul,
.warning-details ul {
  margin: 0;
  padding-left: 20px;
}

.error-details li {
  color: #f56c6c;
  margin-bottom: 4px;
}

.warning-details li {
  color: #e6a23c;
  margin-bottom: 4px;
}

.variable-list {
  max-height: 300px;
  overflow-y: auto;
}

.variable-item {
  padding: 12px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  margin-bottom: 8px;
  background: #fafafa;
}

.variable-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 4px;
}

.variable-type {
  font-size: 12px;
  color: #909399;
  background: #f0f2f5;
  padding: 2px 6px;
  border-radius: 2px;
}

.variable-label {
  font-size: 12px;
  color: #606266;
  margin-bottom: 8px;
}

.doc-content ul {
  margin: 0;
  padding-left: 20px;
}

.doc-content li {
  margin-bottom: 4px;
  line-height: 1.5;
}

.doc-content code {
  background: #f5f7fa;
  padding: 2px 4px;
  border-radius: 2px;
  font-family: 'Courier New', monospace;
  color: #e6a23c;
}
</style>